import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';

class ImageUploadGrid extends StatefulWidget {
  @override
  _ImageUploadGridState createState() => _ImageUploadGridState();
}

class _ImageUploadGridState extends State<ImageUploadGrid> {
  List<File> _images = [];
  final picker = ImagePicker();

  Future<void> _pickImage() async {
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        _images.add(File(image.path));
      });
    }
  }

  void _removeImage(File imageFile) {
    setState(() {
      _images.remove(imageFile);
    });
  }

  Widget _buildImagePickerRow() {
    return Wrap(
      spacing: 5.w,
      runSpacing: 8.w,
      textDirection: TextDirection.rtl, // 让子组件从右往左排
      children: [
        if (_images.length < 8) _buildAddImageButton(),         // 加号始终在右边
        ..._images.map((image) => _buildImageItem(image)).toList(), // 图片往左排
      ],
    );
  }

  Widget _buildImageItem(File imageFile) {
    return Container(
      width: 50.w,
      height: 50.w,
      margin: const EdgeInsets.only(right: 4),
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Image.file(
              imageFile,
              width: 50.w,
              height: 50.w,
              fit: BoxFit.cover,
            ),
          ),
          Positioned(
            top: 0,
            right: 0,
            child: GestureDetector(
              onTap: () => _removeImage(imageFile),
              child: const Icon(Icons.cancel, size: 16, color: Color(0xFFFFFFFF)),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildAddImageButton() {
    return GestureDetector(
      onTap: _pickImage,
      child: Container(
        width: 50.w,
        height:50.w,
        margin: const EdgeInsets.only(right: 4.5),
        decoration: BoxDecoration(
          color: Colors.grey[300],
          borderRadius: BorderRadius.circular(8),
        ),
        child: const Icon(Icons.add),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      // mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 80,
          child: Text(
            "图片凭证",
            style: TextStyle(
              fontSize: 14.w,
              fontWeight: FontWeight.w700)
          ),
        ),
        SizedBox(width: 8.w),
        Expanded(
          child: _buildImagePickerRow()
          ),
      ],
    );
  }
}

